package com.cwz.aop;

import com.cwz.entity.ApiAccessLog;
import com.cwz.entity.User;
import com.cwz.mapper.ApiAccessLogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author wenZhen
 * @create 2024-08-18 16:17
 */

@Aspect
@Component
public class ApiAccessLogAop {


    @Resource
    HttpServletRequest request;


    @Resource
    HttpSession session;


    @Resource
    private ApiAccessLogMapper apiAccessLogMapper;

    //    &&!execution(* com.cwz.controller.UserController.heartBeat())
    @Pointcut("execution(* com.cwz.controller..*.*(..))" +
            "&&!execution(* com.cwz.controller.UserController.heartBeat())" +
            "&&!execution(* com.cwz.controller.DeepSeekController.chatStream(..))" +
            "&&!execution(* com.cwz.controller.UserController.registerUser(..))" +
            "&&!execution(* com.cwz.controller.FileController.upload(..))" +
            "&&!execution(* com.cwz.controller.ChatController.completions(..))")
    public void pointcut() {
    }


    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) {

        ApiAccessLog apiAccessLog = new ApiAccessLog();
        apiAccessLog.setApiName(request.getRequestURI());
        apiAccessLog.setMethod(request.getMethod());
        apiAccessLog.setClientIp(request.getRemoteAddr());
        long start = System.currentTimeMillis();


        try {
            Object proceed = joinPoint.proceed();
            apiAccessLog.setIsException(0);

            return proceed;

        } catch (Throwable e) {
            apiAccessLog.setIsException(1);
            apiAccessLog.setExceptionMessage(e.getMessage());
            return e.getMessage();
        } finally {
            long end = System.currentTimeMillis();
            apiAccessLog.setAccessDuration((end - start));

            User user = (User) session.getAttribute("user");
            apiAccessLog.setUserId(user.getId());
            apiAccessLog.setUsername(user.getUsername());
            apiAccessLog.setRole(user.getRole());

            apiAccessLogMapper.insert(apiAccessLog);
        }


    }


}
